<template>
  <div>
    <p>user: {{ user }}</p>
    <button @click="setUser">vue2_watch</button>
    <hr />
    <p>user: {{ user }}</p>
    <p id="address">address: {{ address }}</p>
    <button @click="setUser">vue3_watch</button>
  </div>
</template>

<script>
import { reactive, watch, ref, watchEffect } from "vue";
/*
export default {
  name: "Vue3Course04Watch",
  data() {
    return {
      user: {
        name: "小明",
        other: {
          address: "郑州市",
        },
      },
    };
  },
  watch: {
    // user(newUser) {
    //   console.log("---", newUser);
    // },
    user: {
      handler(newUser) {
        console.log("---", newUser);
      },
      deep: true, // 开启对象的深度监听，默认对象内部数据的变化不执行
      immediate: true, // 首次就执行watch，默认首次不执行
    },
  },
  methods: {
    setUser() {
      this.user.other.address = "北京市";
      // this.user = { a: 1000 };
    },
  },
};
*/

export default {
  name: "watchView",
  setup() {
    const address = ref("");
    const years = ref(3);
    const user = reactive({
      uname: "小明",
      other: {
        uage: 22,
      },
    });
    const setUser = () => {
      user.uname = "小王";
      address.value = "北京市";
      years.value = 5;
      // user.other.uage = 33;
    };
    // vue3 watch默认开启了深度监听.
    watch(user, (newVal, oldVal) => {
      console.log("---", newVal);
    });
    watch(address, newVal => {
      console.log(newVal);
    });

    // watch一次监听多个值
    watch([address, years], newVal => {
      console.log(newVal);
    });

    // watch也可以只监听响应对象中的某个属性
    watch(
      () => user.other.uage, // 函数的返回值就是要监听的数据
      newVal => {
        console.log(newVal);
      }
    );

    // watchEffect: 自动追踪所用到的响应式数据的变化，默认首次加载也会执行。watch首次加载默认不执行。
    watchEffect(
      () => {
        console.log("触发watachEffect", document.getElementById("address"));
        console.log(address.value);
      },
      {
        flush: "sync", // pre: 默认值，组件更新前调用，此时获取的是旧DOM；post是将watchEffect的执行时机调整到组件渲染之后，此时获取的是新DOM。
      }
    );

    return {
      user,
      setUser,
      address,
    };
  },
};
</script>

<style lang="less" scoped></style>
